package com.ruoyi.lm.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonRpc;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.menu.UrlUtils;
import com.ruoyi.lm.domain.LmLevelpackage;
import com.ruoyi.lm.domain.LmUser;
import com.ruoyi.lm.domain.LmUserlevelpackage;
import com.ruoyi.lm.service.ILmLevelpackageService;
import com.ruoyi.lm.service.ILmUserService;
import com.ruoyi.lm.service.ILmUserlevelpackageService;
import com.ruoyi.lm.service.impl.CoreService;
import com.ruoyi.lm.service.impl.WxTemplateMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;

/**
 * 微信登录控制器
 *
 * @author yuexl
 */
@Controller
@RequestMapping(value = "/phone/lm/wxUserInfo")
public class WxUserInfoController extends BaseController {

    @Autowired
    private CommonRpc commonRpc;

    //微信支付商户开通后 微信会提供appid和appsecret和商户号partner
    @Value("${wxConfig.appId}")
    private String appId;

    @Value("${wxConfig.appSecret}")
    private String appSecret;

    @Value("${wxConfig.partner}")
    private String partner;

    @Value("${wxConfig.partnerKey}")
    private String partnerKey;
    //授权回调
    @Value("${wxConfig.redirectUri}")
    private String redirectUri;

    @Value("${wxConfig.server_url}")
    private String server_url;

    @Autowired
    public ILmUserService lmUserService;

    @Autowired
    public ILmLevelpackageService lmLevelpackageService;

    @Autowired
    private ILmUserlevelpackageService lmUserlevelpackageService;


    /**
     * 微信登录——第一步：获取code
     * 注意每个用户只用授权一次，不用重复授权，授权之后就可以获取相关的用户信息
     *
     * @param response
     */
    @RequestMapping(value = "/wechat/login")
    public void wechatLogin(HttpServletResponse response, HttpServletRequest request)throws Exception {
        String key = request.getParameter("key");
        String pId = request.getParameter("pId");

        try {

            String url = redirectUri + "%3fkey%3d" + key + "%26pId%3d" + pId;
            String qrconnect = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

                response.sendRedirect(qrconnect);
        } catch (Exception e) {
            e.printStackTrace();
            StringBuilder loginPage = new StringBuilder();
            loginPage.append(server_url + "index.html#/?key="+key+"&pId="+pId);
            response.sendRedirect(loginPage.toString());
        }
    }

    /**
     * 微信登录——第二步：通过code换取access_token
     *
     * @param code
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/wechat/callback")
    public void wechatCallback(@RequestParam String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String key = request.getParameter("key");
        String pId = request.getParameter("pId");
        try {
            if (EmptyUtils.isEmpty(pId) || "null".equals(pId)) {
                pId = "0";
            }
            System.out.println(key + "------------------------------------------");
            String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" +
                    code + "&grant_type=authorization_code";
            response.setContentType("text/html;charset=utf-8");
            String json = UrlUtils.loadURL(accessTokenUrl);
            System.out.println("json:" + json);
            Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
            System.out.println("wechatToken-----------------------------------" + wechatToken);
            System.out.println("openid-----------------------------------" + wechatToken.get("openid").toString());
            System.out.println("access_token-----------------------------------" + wechatToken.get("access_token").toString());

            //保存用户信息
            String accessToken = wechatToken.get("access_token").toString();
            String openId = wechatToken.get("openid").toString();
            LmUser user = lmUserService.selectLmUserByOpenId(openId);

            //加载用户信息
            String userInfoJson = sendPost("https://api.weixin.qq.com/sns/userinfo?access_token="
                    + accessToken
                    + "&openid=" + openId, ""
            );
            Map<String, Object> userInfo = JSON.parseObject(userInfoJson, Map.class);
            if(user == null){

                user = new LmUser();
                user.setId(IdWorker.getId());
                user.setOpenId(openId);
                user.setUserPId(pId);
                if(userInfo != null){
                    user.setUserPic(userInfo.get("headimgurl").toString());
                    user.setUserNickname(userInfo.get("nickname").toString());
                }

                LmLevelpackage levelpackage = lmLevelpackageService.selectLmLevelpackageById("821555023015055360");
                user.setPackageTimes(levelpackage.getPackageTimes());

                lmUserService.insertLmUser(user);

                //保存用户购买套餐记录
                LmUserlevelpackage userlevelpackage = new LmUserlevelpackage();
                userlevelpackage.setId(IdWorker.getId());
                userlevelpackage.setUserId(user.getId());
                userlevelpackage.setPackageId("821555023015055360");
                userlevelpackage.setPackageTimes(levelpackage.getPackageTimes());
                userlevelpackage.setCreateTime(new Date());
                userlevelpackage.setTranstionId("");
                userlevelpackage.setPackagePrice(Float.valueOf(levelpackage.getPackagePrice()));
                lmUserlevelpackageService.insertLmUserlevelpackage(userlevelpackage);
            }

            user.setUserPic(userInfo.get("headimgurl").toString());
            user.setUserNickname(userInfo.get("nickname").toString());
            lmUserService.updateLmUser(user);

            //返回前端处理
            StringBuilder loginPage = new StringBuilder();
            loginPage.append(server_url + "index.html#/authorization");
            loginPage.append("?openid=" + wechatToken.get("openid").toString());
            loginPage.append("&key=" + key);
            loginPage.append("&userId=" + user.getId());
            loginPage.append("&userPhone=" + user.getUserPhone());


            System.out.println(loginPage.toString());
            response.sendRedirect(loginPage.toString());
        }catch (Exception e){
            e.printStackTrace();
            StringBuilder loginPage = new StringBuilder();
            loginPage.append(server_url + "index.html#/?key="+key+"&pId="+pId);
            response.sendRedirect(loginPage.toString());
        }

    }


    /**
     * 发送短信验证码
     * @param phone
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wechat/sendMagCode")
    @ResponseBody
    public AjaxResult bindPhone(String phone)throws Exception {
        String code = commonRpc.sendBatchSms(phone);
        return success("短信发送成功",code);
    }

    /**
     * 绑定手机号
     * @param userId
     * @param phone
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wechat/bindPhone")
    @ResponseBody
    public AjaxResult bindPhone(String userId, String phone)throws Exception {
        LmUser user = new LmUser();
        user.setId(userId);
        user.setUserPhone(phone);
        lmUserService.updateLmUser(user);
        return success();
    }


    public static String sendPost(String url, String param) throws Exception {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数

            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;

    }

    public static void main(String args[])throws Exception{

    }

    @RequestMapping(value = "/wechat/send_template_message")
    @ResponseBody
    public AjaxResult send_template_message()throws Exception {
        WxTemplateMsgService wxTemplateMsgService = new WxTemplateMsgService();
        wxTemplateMsgService.send_template_message("okvls1XIgoZUHW3i1Z4j7lcad74o", appId, appSecret, "活动报名");
        return success();
    }
}

